<template>
    <div class="bedroom-visualization">
        <!-- 标题 -->
        <el-row class="header" justify="center" align="middle">
            <el-col :span="24">
                <h2>养老院床位状态可视化</h2>
            </el-col>
        </el-row>

        <!-- 楼层选择 -->
        <el-row class="filter" justify="center" align="middle">
            <el-col :span="8">
                <el-select v-model="selectedBuilding" placeholder="选择楼栋" @click="getBedInfoByBuilding">
                    <el-option v-for="(building, index) in cells" :key="index" :label="building.value"></el-option>
                </el-select>
            </el-col>

            <el-col :span="8">
                <el-select v-model="selectedFloor" placeholder="选择楼层" @click="getBedInfoByFloor">
                    <el-option v-for="(floor, index) in floorValues" :key="index" :label="floor.value"></el-option>
                </el-select>
            </el-col>
        </el-row>

        <!-- 床位使用比例图 -->
        <div class="chart-container">
            <el-row>
                <el-col :span="24">
                    <div ref="bedUsageChart" class="chart"></div>
                </el-col>
            </el-row>
        </div>

        <!-- 房间床位列表 -->
        <el-row class="room-list" justify="center" align="middle">
            <el-col :span="24">
                <el-table :data="roomData" style="width: 100%">
                    <el-table-column prop="roomNumber" label="房间号" width="150" />
                    <el-table-column prop="totalBeds" label="总床位" width="100" />
                    <el-table-column prop="usedBeds" label="已使用" width="100" />
                    <el-table-column prop="genderBalance" label="性别比例" width="150" />
                </el-table>
            </el-col>
        </el-row>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import type { Room } from '@/API/interface/bedStatus';
import { getBedInfoByFloorApi, getBedInfoByBuildingApi } from '@/API/interface/bedStatus'
import type { Bed } from '../../API/interface/bedManagement'
import { getAllBeds } from '@/API/interface/bedManagement'


const roomData = ref<Room[]>([]);
const selectedBuilding = ref('');
const selectedFloor = ref('');
const bedUsageChart = ref<echarts.ECharts | null>(null);

// 楼栋获取数据
const getBedInfoByBuilding = async () => {
    if (!selectedBuilding.value) {
        return
    } else { 
        const res = await getBedInfoByBuildingApi({ selectedBuilding: selectedBuilding.value });
        console.log('楼栋返回数据', res);
    }
}
// 获取楼层数据
const getBedInfoByFloor = async () => {
    if (!selectedBuilding.value || !selectedFloor.value) {
        return
    } else {
        const res = await getBedInfoByFloorApi(selectedBuilding.value, selectedFloor.value)
        console.log('楼层返回数据', res);
    }

}
// 更新床位使用比例图
const updateBedUsageChart = () => {
    const usedBeds = roomData.value.reduce((acc, room) => acc + room.usedBeds, 0);
    const totalBeds = roomData.value.reduce((acc, room) => acc + room.totalBeds, 0);
    const usagePercentage = (usedBeds / totalBeds) * 100;

    const option = {
        title: {
            text: '床位使用比例',
            subtext: `使用率: ${usagePercentage.toFixed(2)}%`,
            left: 'center',
        },
        tooltip: {
            trigger: 'item',
        },
        series: [
            {
                name: '床位使用',
                type: 'pie',
                radius: '50%',
                data: [
                    { value: usedBeds, name: '已使用' },
                    { value: totalBeds - usedBeds, name: '空闲' },
                ],
                emphasis: {
                    itemStyle: {
                        borderColor: '#fff',
                        borderWidth: 2,
                    },
                },
            },
        ],
    };

    bedUsageChart.value?.setOption(option);
};

// 初始楼和用户编号
const allBedInfo = ref([]);  //获取所有床位信息
const filteredBedrooms = ref<Bed[]>([]); // 修正为 Bed 类型
//获取所有床位信息
onMounted(async () => {
    //初始化图表
    bedUsageChart.value = echarts.init(document.querySelector('.chart') as HTMLElement);
    if (selectedBuilding.value && selectedFloor.value) {
        getBedInfoByFloor();
    }

    const res = await getAllBeds();
    // console.log("获取所有床位", res.data);
    allBedInfo.value = res.data.data;  //把所有床位信息存到allBedInfo里面
    console.log("allBedInfo", allBedInfo.value);
    // 将allBedInfo中的数据映射到bedrooms中
    filteredBedrooms.value = allBedInfo.value.map((bed: any) => ({
        bedId: bed.bedId,
        buildingNo: bed.buildingNo,
        roomNo: bed.roomNo,
        floorNo: bed.floorNo,
        bedNo: bed.bedNo,
        assignedUserGender: bed.status === '空' ? '' : bed.gender, // 如果床位状态为空，则分配用户为空
        price: bed.price,
    }));
    // 动态填充楼房、楼层、房间和床位信息
    const uniqueBuildings = new Set<string>();
    const uniqueFloors = new Set<string>();
    const uniqueRooms = new Set<string>();
    const uniqueBeds = new Set<string>();

    res.data.data.forEach((bed: any) => {
        uniqueBuildings.add(bed.buildingNo);
        uniqueFloors.add(bed.floorNo);
        uniqueRooms.add(bed.roomNo);
        uniqueBeds.add(bed.bedNo);
    });

    cells.value = Array.from(uniqueBuildings).map(building => ({ value: building }));
    floorValues.value = Array.from(uniqueFloors).map(floor => ({ value: floor }));
    roomValues.value = Array.from(uniqueRooms).map(room => ({ value: room }));
    bedValues.value = Array.from(uniqueBeds).map(bed => ({ value: bed }));

});
const cells = ref([
    { value: '' }
]);

const floorValues = ref([
    { value: '' }
]);
const roomValues = ref([
    { value: '' }
]);
const bedValues = ref([
    { value: '' }
]);
</script>

<style lang="less" scoped>
.bedroom-visualization {
    padding: 20px;
}

.header {
    margin-bottom: 20px;
}

.filter {
    margin-bottom: 20px;
}

.chart-container {
    margin-top: 20px;
    width: 100%;
    height: 400px;
}

.room-list {
    margin-top: 20px;
}

.chart {
    width: 100%;
    height: 400px;
}
</style>